package com.ruoyi.yipaiju.service.impl;

import com.ruoyi.common.constant.BizConstants;
import com.ruoyi.common.core.domain.entity.XcxRole;
import com.ruoyi.common.core.domain.entity.XcxUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.yipaiju.domain.Roles;
import com.ruoyi.yipaiju.domain.WXOpenid;
import com.ruoyi.yipaiju.mapper.XcxUserMapper;
import com.ruoyi.yipaiju.service.IRolesService;
import com.ruoyi.yipaiju.service.IXcxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 小程序用户Service业务层处理
 * 
 * @author liuwp
 * @date 2023-03-01
 */
@Service
public class XcxUserServiceImpl implements IXcxUserService 
{
    @Autowired
    private XcxUserMapper xcxUserMapper;
    @Autowired
    private IRolesService rolesService;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询小程序用户
     * 
     * @param id 小程序用户主键
     * @return 小程序用户
     */
    @Override
    public XcxUser selectXcxUserById(Long id)
    {
        return xcxUserMapper.selectXcxUserById(id);
    }

    /**
     * 查询小程序用户列表
     * 
     * @param xcxUser 小程序用户
     * @return 小程序用户
     */
    @Override
    public List<XcxUser> selectXcxUserList(XcxUser xcxUser)
    {
        return xcxUserMapper.selectXcxUserList(xcxUser);
    }
    @Override
    public List<XcxUser> selectXcxUserList1(XcxUser xcxUser)
    {
        return xcxUserMapper.selectXcxUserList1(xcxUser);
    }

    @Override
    public List<XcxUser> selectXcxUserListIds(List<Long> ids) {
        return xcxUserMapper.selectXcxUserListIds(ids);
    }

    /**
     * 根据业务主键查询一条记录：小程序用户
     *
     * @param xcxUser 小程序用户
     * @return 小程序用户
     */
    @Override
    public XcxUser selectOneXcxUser(XcxUser xcxUser)
    {
        return xcxUserMapper.selectOneXcxUser(xcxUser);
    }

    /**
     * 新增小程序用户
     * 
     * @param xcxUser 小程序用户
     * @return 结果
     */
    @Override
    public int insertXcxUser(XcxUser xcxUser)
    {
        xcxUser.setCreateTime(DateUtils.getNowDate());
        return xcxUserMapper.insertXcxUser(xcxUser);
    }

    /**
     * 修改小程序用户
     * 
     * @param xcxUser 小程序用户
     * @return 结果
     */
    @Override
    public int updateXcxUser(XcxUser xcxUser)
    {
        xcxUser.setUpdateTime(DateUtils.getNowDate());
        return xcxUserMapper.updateXcxUser(xcxUser);
    }

    @Override
    public int updateXcxUserCondition(XcxUser xcxUser, XcxUser xcxUserCondition)
    {
        xcxUser.setUpdateTime(DateUtils.getNowDate());
        return xcxUserMapper.updateXcxUserCondition(xcxUser, xcxUserCondition);
    }

    /**
     * 批量删除小程序用户
     * 
     * @param ids 需要删除的小程序用户主键
     * @return 结果
     */
    @Override
    public int deleteXcxUserByIds(Long[] ids)
    {
        return xcxUserMapper.deleteXcxUserByIds(ids);
    }

    /**
     * 删除小程序用户信息
     * 
     * @param id 小程序用户主键
     * @return 结果
     */
    @Override
    public int deleteXcxUserById(Long id)
    {
        return xcxUserMapper.deleteXcxUserById(id);
    }

    /**
     * 条件删除小程序用户
     *
     * @param xcxUser 小程序用户
     * @return 结果
     */
    @Override
    public int deleteXcxUserByCondition(XcxUser xcxUser)
    {
        return xcxUserMapper.deleteXcxUserByCondition(xcxUser);
    }

    @Override
    public XcxUser xcxUserLogin(WXOpenid wxOpenid) {
        // 查询用户是否存在
        XcxUser xcxUser = selectOneXcxUser(Builder.of(XcxUser::new)
                .with(XcxUser::setAppid, wxOpenid.getAppid())
                .with(XcxUser::setOpenid, wxOpenid.getOpenid())
                .build());
        if (xcxUser == null){
            xcxUser = new XcxUser();
            xcxUser.setAppid(wxOpenid.getAppid());
            xcxUser.setOpenid(wxOpenid.getOpenid());
            xcxUser.setUnionid(wxOpenid.getUnionid());
            xcxUser.setSessionKey(wxOpenid.getSession_key());
            // 随机生成默认微信昵称和头像 因为授权已经获取不到了
            xcxUser.setNickname(Md5Utils.hash(xcxUser.getOpenid()).substring(8, 16));
            String avatarUrl = sysConfigService.selectConfigByKey("biz.user.avatar_url");
            avatarUrl = StringUtils.isEmpty(avatarUrl) ? BizConstants.User.AVATAR_URL : avatarUrl;
            xcxUser.setAvatarUrl(avatarUrl);
            insertXcxUser(xcxUser);
        }
        return xcxUser;
    }

    @Override
    public List<XcxRole> selectXcxRoleByUserId(Long userId) {
        List<Roles> roles = xcxUserMapper.selectXcxRoleByUserId(userId);
        List<XcxRole> xcxRoles = new ArrayList<>();
        for (Roles role : roles) {
            XcxRole xcxRole = new XcxRole();
            BeanUtils.copyProperties(role, xcxRole);
            xcxRoles.add(xcxRole);
        }
        return xcxRoles;
    }

    @Override
    public Map<Long, XcxUser> getXcxUserByIds(List<Long> ids) {
        if (ids == null || ids.size() == 0) return new HashMap<>();
        // 批量查询用户信息
        List<XcxUser> xcxUsers = selectXcxUserListIds(ids);
        return xcxUsers.stream().collect(Collectors.toMap(XcxUser::getId, item -> item, (value1, value2) -> value2));
    }

    @Override
    public XcxUser getXcxUserLogin(XcxUser xcxUser) {
        // 获取权限列表
        List<XcxRole> xcxRoles = selectXcxRoleByUserId(xcxUser.getId());
        xcxUser.setGranted_role_set(xcxRoles);
        if (xcxUser.getActive_role_id() != null){
            Roles roles = rolesService.selectRolesById(xcxUser.getActive_role_id());
            if (roles != null){
                XcxRole xcxRole = new XcxRole();
                BeanUtils.copyProperties(roles, xcxRole);
                xcxUser.setActive_role(xcxRole);
                xcxUser.setRole_code(roles.getCode());
            }
        }
        updateXcxUser(xcxUser);
        return xcxUser;
    }

}
